<template>
  <div id="userRegisterView">
    <a-space style="margin-bottom: 32px" size="medium">
      <img
        src="../assets/logo.png"
        style="width: 32px"
        class="logo"
        alt="logo"
      />
      <span style="font-family: 'consolas', serif; font-size: 20px">
        Online Chat
      </span>
    </a-space>
    <a-form
      style="max-width: 360px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit-success="handleSubmit"
    >
      <a-form-item hide-label>
        <span style="font-size: 18px">用户注册</span>
      </a-form-item>
      <a-form-item
        field="username"
        label="账号"
        tooltip="账户是你的唯一标识，注册后不可更改。可由字母、数字、下划线组成，长度应在4到10个字符之间。"
        :hide-asterisk="true"
        :rules="usernameRules"
        :validate-trigger="['blur']"
      >
        <a-input
          v-model="form.username"
          placeholder="请输入账号"
          allow-clear
          spellcheck="false"
        >
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        label="密码"
        tooltip="密码必须同时包含字母、数字以及特殊字符，长度应在8到16个字符之间。"
        :hide-asterisk="true"
        :rules="[
          { required: true, message: '密码不能为空' },
          { minLength: 8, message: '不能小于8个字符' },
          { maxLength: 16, message: '不能多于16个字符' },
          { match: /^[a-zA-Z0-9\W_]+$/, message: '存在非法字符' },
          {
            match: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_])[\w\W]+$/,
            message: '密码过于简单',
          },
        ]"
        :validate-trigger="['blur']"
      >
        <a-input-password
          v-model="form.password"
          placeholder="请输入密码"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item
        field="checkPassword"
        label="确认密码"
        :hide-asterisk="true"
        :rules="[
          { required: true, message: '请再次输入密码' },
          { validator: checkSamePass, message: '两次输入密码不一致' },
        ]"
        :validate-trigger="['blur']"
      >
        <a-input-password
          v-model="form.checkPassword"
          placeholder="请再次输入密码"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" long>注册</a-button>
      </a-form-item>
      <a-form-item>
        <a-row style="width: 100%">
          <a-col style="display: flex; justify-content: center">
            <a-link style="font-size: small" href="/login" :hoverable="false">
              已有账号？立即登录
            </a-link>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { useRouter } from "vue-router";
import errorModal from "@/utils/modal";
import { successNotification } from "@/utils/notification";
import axios from "axios";
import { UserRegisterRequest } from "@/models/UserRegisterRequest";

/**
 * 表单信息
 */
const form: UserRegisterRequest = reactive({
  username: "",
  password: "",
  checkPassword: "",
});

const usernameRules = [
  { required: true, message: "账户不能为空！" },
  { minLength: 4, message: "不能小于4个字符！" },
  { maxLength: 10, message: "不能多于10个字符！" },
  { match: /^[A-Za-z0-9_]+$/, message: "存在非法字符！" },
  {
    validator: async (value: string, cb: (arg0: string) => void) => {
      const res = await axios({
        method: "get",
        url: "http://localhost:8081/user/check/username",
        params: {
          username: value,
        },
      });
      if (res.data.code === 0) {
        if (res.data === false) {
          cb("账号已存在，再想一个吧！");
        }
      } else {
        errorModal("系统错误", "错误信息：" + res.data.message);
      }
    },
  },
];

function checkSamePass(
  value: string | undefined,
  callback: (error?: string) => void
) {
  if (value !== form.password) {
    callback("两次输入密码不一致");
  } else {
    callback();
  }
}

const router = useRouter();

const handleSubmit = async () => {
  const res = await axios({
    method: "post",
    url: "http://localhost:8081/user/register",
    data: form,
  });
  if (res.data.code === 0) {
    successNotification("注册成功，请登录！");
    await router.push({
      path: "/login",
      replace: true,
    });
  } else {
    errorModal("注册失败", "错误信息：" + res.data.message);
  }
};
</script>

<style scoped>
#userRegisterView {
  width: 352px;
  margin-top: 128px;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid var(--color-neutral-4);
  border-radius: 10px;
  box-shadow: 4px 4px 8px var(--color-neutral-4);
  padding: 24px 32px 32px;
}
</style>
